﻿using GoodDotNet.IService;
using GoodDotNet.Core.Entity;
using GoodDotNet.Core.Model;
using GoodDotNet.Core.Data;

namespace GoodDotNet.Service
{
    public class AdminUserRoleService :BaseService,AdminUserRoleIService
    {
        public AdminUserRoleService(UnitOfWork _unitOfWork) : base(_unitOfWork)
        {
        }

        public void Add(ParInsertAdminUserRoleModel pars)
		{
			AdminUserRole entity=new AdminUserRole();
			
			entity.RoleId=pars.role_id;
			
			entity.AdminId=pars.admin_id;
			
			 
		    _unitOfWork.AdminUserRoleRepository.Add(entity);
		    _unitOfWork.SaveChanges();
		
		}
		
				
		
		public List<AdminUserRole>? GetListByRole( int role_id)
		{
			
			var list = _unitOfWork.AdminUserRoleRepository.GetList(a=>a.RoleId == role_id);
			
			return list;
		  
		}

        public List<AdminUserRole>? GetListByAdmin(int admin_id)
        {

            var list = _unitOfWork.AdminUserRoleRepository.GetList(a => a.AdminId == admin_id);

            return list;

        }
        public int Delete(ParDeleteAdminUserRoleModel pars)
		{
				System.FormattableString sql = $"delete from admin_user_role where  id=pars.id";
				return _unitOfWork.AdminUserRoleRepository.ExecuteSql(sql);
		}
        /// <summary>
        /// 更新用户角色
        /// </summary>
        /// <param name="par"></param>
        public void UpdateUserRole(ParAdminRoleUpdateUserRole par)
        {
            var roles = _unitOfWork.AdminUserRoleRepository.GetList(a => a.AdminId == par.UserId);
            if (par.RoleIDs.Length == 0)
            {
                roles.ForEach(role =>
                {
                    _unitOfWork.AdminUserRoleRepository.Remove(role);
                });
            }
            else
            {

                roles.ForEach(role =>
                {
                    bool inArray = false;
                    for (int i = 0; i < par.RoleIDs.Length; i++)
                    {
                        if (par.RoleIDs[i] == role.RoleId)
                        {
                            inArray = true;
                            break;
                        }
                    }
                    if (!inArray)
                    {
                        _unitOfWork.AdminUserRoleRepository.Remove(role);
                    }

                });
                for (int i = 0; i < par.RoleIDs.Length; i++)
                {
                    var role = roles.Where(a => a.RoleId == par.RoleIDs[i]).FirstOrDefault();
                    if (role == null)
                    {
                        AdminUserRole adminUserRole = new AdminUserRole();
                        adminUserRole.RoleId = par.RoleIDs[i];
                        adminUserRole.AdminId = par.UserId;
                        _unitOfWork.AdminUserRoleRepository.Add(adminUserRole);
                    }
                }
            }
            _unitOfWork.SaveChanges();
        }
    }
}
